<?php
require_once(SITE_ROOT . 'class/db/DBAlliance.class.php');
require_once(SITE_ROOT . 'class/db/DBAllianceMember.class.php');
require_once(SITE_ROOT . 'class/db/DBCountry.class.php');
require_once(SITE_ROOT . 'class/db/DBDivision.class.php');
require_once(SITE_ROOT . 'class/db/DBLeague.class.php');
require_once(SITE_ROOT . 'class/db/DBTeam.class.php');
require_once(SITE_ROOT . 'class/db/DBFlag.class.php');
require_once(SITE_ROOT . 'class/bean/Country.class.php');
require_once(SITE_ROOT . 'class/bean/Division.class.php');
require_once(SITE_ROOT . 'class/bean/League.class.php');
require_once(SITE_ROOT . 'class/bean/Team.class.php');
require_once(SITE_ROOT . 'class/logic/HoCTableRow.class.php');
require_once(SITE_ROOT . 'class/logic/LogicCoolness.class.php');
require_once(SITE_ROOT . 'lib/PHT.php');
require_once(SITE_ROOT . 'config/constants.conf.php');

class LogicHoC {

	private static $instance;
	
	// private constructor
	private function __construct() {}

	// the getInstance() method returns a single instance of the object
	public static function getInstance() {
		if(!isset(self::$instance)) {
			self::$instance = new self;
		}
		return self::$instance;
	}
	
	public function createHoCTable($term, $type, $countryID, $divisionID, $leagueID, $allianceID, $month, $year, $startindex, $endindex) {
		$table = array();
						
		$teams = $this->getRanking($term, $type, $countryID, $divisionID, $leagueID, $allianceID, $month, $year, $startindex, $endindex);
		if (count($teams) > 0) {
			foreach ($teams as $index => &$team) {
				$row = new HoCTableRow($index+$startindex+1, $team, $term, $type);
				$table[$index+1] = $row;
			}
		}
		return $table;
	}
	
	public function getCountries() {
		$dbcountry = new DBCountry();
		$countries = $dbcountry->getCountries("name");
		return $countries;
	}
	
	public function getDivisions($countryID = null) {
		if ($countryID === null || $countryID == 0) {
			$dbdivision = new DBDivision();
			$divisions = $dbdivision->getDivisions();
		}
		else {
			$country = new Country();
			$country->setCountryID($countryID);
			$dbdivision = new DBDivision();
			$divisions = $dbdivision->getDivisionsByCountry($country);
		}
		return $divisions;
	}
	
	public function getLeagues($countryID, $divisionID) {
		$country = new Country();
		$country->setCountryID($countryID);
		$division = new Division();
		$division->setDivisionID($divisionID);
		$division->setCountry($country);
		$dbleague = new DBLeague();
		$leagues = $dbleague->getLeaguesByDivision($division);
		return $leagues;
	}
	
	public function getLeague($leagueID) {
		$dbleague = new DBLeague();
		$league = $dbleague->getLeague($leagueID);
		return $league;
	}
	
	public function getAlliances() {
		$dballiance = new DBAlliance();
		$alliances = $dballiance->getAlliances();
		return $alliances;
	}
    	
	public function getMonths() {
		$months = array();
		$months[0] = "Any";	
		for ($i=1; $i<13; $i++) {
			$months[$i] = date("F", mktime(0, 0, 0, $i, 1, 2000));
		}
		return $months;
	}
	
	public function getYears($month = null) {
		$years = array();
		if ($month === null || $month == 0) {
			$years[0] = "Any";
		}
		for ($i=date("Y", time()); $i>=1997; $i--) {
			$years[$i] = $i;
		}
		return $years;
	}
	
	public function getRankingCount($countryID, $divisionID, $leagueID, $allianceID, $month, $year) {
		if ($month != 0 || $year != 0) {
			if ($month == 0) {
				$frommonth = 1;
				$tomonth = 1;
				$fromyear = $year;
				$toyear = $year + 1;
			}
			else if ($month != 0) {
				$frommonth = $month;
				$tomonth = $month + 1;
				$fromyear = $year;
				$toyear = $year;
			}			
			$fromdate = mktime(0, 0, 0, $frommonth, 1, $fromyear);
			$todate = mktime(0, 0, 0, $tomonth, 1, $toyear);
		}
		
		$dbteam = new DBTeam();
		return $dbteam->getCountForHoC($countryID, $divisionID, $leagueID, $allianceID, $fromdate, $todate);
	}
	
	public function getRanking($term, $type, $countryID, $divisionID, $leagueID, $allianceID, $month, $year, $startindex, $endindex) {
		$orderby = $this->getOrderBy($term, $type);
		
		if ($month != 0 || $year != 0) {
			if ($month == 0) {
				$frommonth = 1;
				$tomonth = 1;
				$fromyear = $year;
				$toyear = $year + 1;
			}
			else if ($month != 0) {
				$frommonth = $month;
				$tomonth = $month + 1;
				$fromyear = $year;
				$toyear = $year;
			}			
			$fromdate = mktime(0, 0, 0, $frommonth, 1, $fromyear);
			$todate = mktime(0, 0, 0, $tomonth, 1, $toyear);
		}
		
		$dbteam = new DBTeam();
		return $dbteam->getTeamsForHoC($orderby, $countryID, $divisionID, $leagueID, $allianceID, $fromdate, $todate, $startindex, $endindex);
	}

	public function update($teamID) {
		$logicCoolness = LogicCoolness::getInstance();
		$logicCoolness->autoUpdate($teamID, false);
	}
	
	private function getOrderBy($term, $type) {
		if ($term == CONST_FLAG) {
			switch ($type) {
				case CONST_AWAY:	return "away_flags";break;
				case CONST_HOME:	return "home_flags";break;
				case CONST_AND:		return "and_flags";break;
				case CONST_OR:		return "or_flags";break;
				case CONST_PLUS:	return "plus_flags";break;
				default:			return "away_flags";break;
			}		
		}
		else {
			switch ($type) {
				case CONST_AWAY:	return "away_coolness";break;
				case CONST_HOME:	return "home_coolness";break;
				case CONST_AND:		return "and_coolness";break;
				case CONST_OR:		return "or_coolness";break;
				case CONST_PLUS:	return "plus_coolness";break;
				default:			return "away_coolness";break;
			}
		}
	}
	
	public function fetchAlliance($allianceID) {
		$HT = $_SESSION['HT'];
	
		if ($HT instanceof CHPPConnection) {
			$htAlliance = $HT->getAllianceDetails($allianceID);
			if ($htAlliance != null || $htAlliance->getId() != 0) {				
				$htAllianceMembers = $HT->getAllianceMembers($allianceID);
								
				$alliance = new Alliance($htAlliance->getId(), $htAlliance->getName());
				$dballiance = new DBAlliance();
				$dballiance->saveAlliance($alliance);
				
				$dballiancemember = new DBAllianceMember();
				$dballiancemember->deleteAllianceMembership($alliance);
				
				if ($htAllianceMembers->getNumberMembers() >= 100) {
					$HT->clearAlliancesMembers();
					$letters = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0");
					foreach ($letters as $letter) {
						$htAllianceMembers = $HT->getAllianceMembersByLetter($allianceID, $letter);
						$alliance->setNumberMembers($alliance->getNumberMembers() + $htAllianceMembers->getNumberMembers());
						$this->fetchAllianceMembers($alliance, $htAllianceMembers, $HT);
					}
				}
				else {
					$alliance->setNumberMembers($alliance->getNumberMembers() + $htAllianceMembers->getNumberMembers());
					$this->fetchAllianceMembers($alliance, $htAllianceMembers, $HT);
				}
			}
			return $alliance;
		}
		else throw new Exception("(0)");
	}
	
	private function fetchAllianceMembers(&$alliance, &$htAllianceMembers, &$HT) {
		$dbteam = new DBTeam();
		$teams = new ArrayObject();
		$dballiancemember = new DBAllianceMember();
		$alliancemembers = new ArrayObject();
		
		for ($i=1; $i<=$htAllianceMembers->getNumberMembers(); $i++) {
			$team = $dbteam->getTeamByUserID($htAllianceMembers->getMember($i)->getId());				
			if (!isset($team)) {
				$htTeam = $HT->getTeamByUserId($htAllianceMembers->getMember($i)->getId());
				
				$team = new Team($htTeam->getTeamId(), $htTeam->getTeamName());
				$team->setUserID($htTeam->getUserId());
				$team->setUserName($htTeam->getLoginName());
				$team->setActivationDate($htTeam->getActivationDate());
				
				$league = new League();
				if ($htTeam->isLeagueLevelAvailable()) {
					$league->setLeagueID($htTeam->getLeagueLevelId());
				}
				//else throw new LeagueNotAvailableException($team);
				$team->setLeague($league);
				
				$team->addAlliance($alliance);
				$teams->append($team);
			}
			else {
				$team->addAlliance($alliance);
				$alliancemembers->append($team);
			}						
		}
		$dbteam->saveTeams($teams);
		$dballiancemember->saveAllianceMemberships($alliancemembers);
		$HT->clearTeams();
		$HT->clearAlliancesMembers();
		$HT->clearAlliancesMembersByLetters();
	}
	
	public function fetchLeague($leagueID) {
		$dbleague = new DBLeague();
		$league = $dbleague->getLeague($leagueID);
		
		$dbteam = new DBTeam();
		$teams = new ArrayObject();
		
		$HT = $_SESSION['HT'];
	
		if ($HT instanceof CHPPConnection) {
			$htLeague = $HT->getLeague($leagueID);
			
			for ($i=1; $i<=8; $i++) {
				$htLeagueTeam = $htLeague->getTeam($i);
				$team = $dbteam->getTeamByID($htLeagueTeam->getTeamId());
				
				if (!isset($team)) {
					$htTeam = $HT->getTeam($htLeagueTeam->getTeamId());
					
					if ($htTeam->isBot()) {
						$dbteam->deleteTeamByID($htTeam->getTeamId());
						$dballiancemember = new DBAllianceMember();
						$dballiancemember->deleteAllianceMembershipByTeamID($teamID);
						$dbflag = new DBFlag();
						$dbflag->deleteFlagsByTeamID($teamID);
					}
					else {
						$team = new Team($htTeam->getTeamId(), $htTeam->getTeamName());
						$team->setUserID($htTeam->getUserId());
						$team->setUserName($htTeam->getLoginName());
						$team->setActivationDate($htTeam->getActivationDate());
						
						$league = new League($leagueID);
						$team->setLeague($league);
						
						$teams->append($team);
					}					
				}
			}
			if (count($teams) > 0) $dbteam->saveTeams($teams);
			
			$HT->clearTeams();
			$HT->clearLeague($leagueID);
			
			return $league;
		}
		else throw new Exception("(0)");
	}
	
}

?>